package com.dyz.leetcode._12_linkedList;

import com.dyz.leetcode.ListNode;

public class _61_rotateRight {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null || head.next==null||k==0){return head;}

        int len = 0;
        ListNode curr = head;
        while (curr!=null){
            len++;
            curr = curr.next;
        }
        if(k%len==0){return head;}
        k=k%len;

        ListNode newHead = reverse(head);

        ListNode kthNode = newHead;
        for (int i = 0; i < k - 1; i++) {
            kthNode = kthNode.next;
        }
        ListNode nextHead = kthNode.next;
        kthNode.next = null;
        ListNode retHead = reverse(newHead);
        newHead.next = reverse(nextHead);

        return retHead;

    }
    private ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    public ListNode rotateRight2(ListNode head, int k) {
        if (head == null || head.next == null || k == 0) {return head;}
        int len = 1;
        ListNode lastNode = head;
        while (lastNode.next != null) {
            len++;
            lastNode = lastNode.next;
        }
        if (k % len == 0) {return head;}
        k = k % len;

        ListNode newTail = head;
        for (int i = 0; i < len - k - 1; i++) {
            newTail = newTail.next;
        }

        ListNode newHead = newTail.next;
        newTail.next = null;
        lastNode.next = head;

        return newHead;
    }
}
